package nl.tue.be.ds.duraark.bSDD.ontology;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

import org.codehaus.jackson.JsonNode;

import com.hp.hpl.jena.ontology.DatatypeProperty;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Resource;

import nl.tue.be.ds.duraark.bSDD.DataBaseStorageUnit;

public class ClassProcessor {

	private OntModel ontModel;
	private OntClass ontoClass;
	private String ns0;
	private PropertyProcessor propertyProcessor;

	public ClassProcessor(OntModel ontModel, OntClass ontoClass, String ns0,
			PropertyProcessor propertyProcessor) {
		super();

		this.ontModel = ontModel;
		this.ontoClass = ontoClass;
		this.ns0 = ns0;
		this.propertyProcessor = propertyProcessor;
	}

	public void classProcess(DataBaseStorageUnit dbSunit) {

		JsonNode jsNodeCon = dbSunit.getConceptJN();
		conceptProcess(jsNodeCon);

		HashMap<String, String> parentsRel = new HashMap<String, String>();
		parentsRel = dbSunit.getParentsGuidMap();
		relProcess(parentsRel);

	}

	private void conceptProcess(JsonNode jsNodeCon) {

		Iterator<Entry<String, JsonNode>> iter = jsNodeCon.getFields();

		while (iter.hasNext()) {
			Entry<String, JsonNode> subNode = iter.next();

			if (subNode.getValue().isTextual()) {
				propertyProcessor.textValueSubNodeProcess(subNode);
				// TODO
			} else if (subNode.getValue().isObject()) {
				String key = subNode.getKey();
				DatatypeProperty datatypeProperty = ontModel
						.createDatatypeProperty(ns0 + key);
				Resource r = propertyProcessor
						.objectValueSubNodeProcess(subNode);
				ontoClass.addProperty(datatypeProperty, r);

			} else if (subNode.getValue().isArray()) {
				propertyProcessor.arrayValueSubNodeProcess(subNode);

			}
		}

	}

	private void relProcess(HashMap<String, String> parentsRel) {

		if ((parentsRel != null) && (parentsRel.size() != 0)) {
			Set<Entry<String, String>> conInRelGuidRelTypePairSet = parentsRel
					.entrySet();
			Iterator<Entry<String, String>> iter = conInRelGuidRelTypePairSet
					.iterator();
			while (iter.hasNext()) {
				Entry<String, String> conInRelGuidRelTypePair = iter.next();

				// System.out.println("conInRelGuid : " +
				// conInRelGuidRelTypePair.getKey());
				// System.out.println("conType : " +
				// conInRelGuidRelTypePair.getValue());

				if (conInRelGuidRelTypePair.getValue().equals("SPECIALIZES")) {
					String supConGuid = conInRelGuidRelTypePair.getKey();
					OntClass supClass = ontModel
							.createClass(OntoGenerator.ontoNamespace
									+ supConGuid);
					ontoClass.addSuperClass(supClass);
				} else {
					propertyProcessor
							.objectPropertyProcess(conInRelGuidRelTypePair);
				}
			}
		}

	}

}
